import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios';
import { stat } from 'fs';

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list:[],
    defaultChecked:false,
  },
  mutations: {
    async getList(state,payload){
      const {data:res} = await axios.get('./shop.json')
      state.list = res.result
    },
    plus(state,payload){
      payload.num++
    },
    substract(state,payload){
      if( payload.num <= 1 ){
        payload.num = 1
      }else{
        payload.num --
      }
    },
    del(state,payload){
      state.list =  state.list.filter(item=>{
        return item._id !== payload._id
      })
    },
    chose(state){
      var len = 0
      state.list.forEach(item=>{
        if( item.checked == true ){
          len++
        }
      })
      if( len == state.list.length ){
        state.defaultChecked = true
      }else{
        state.defaultChecked = false
      }
    },
    choseAll(state){
      state.defaultChecked = !state.defaultChecked
      state.list.forEach(item=>{
        item.checked = state.defaultChecked
      })
    },
    sort(state){
      var arr = []
      state.list.forEach(item=>{
        arr.push(item.price)
      })
      arr.sort((a,b)=>{
        return a-b
      })
      var nlist = []
      arr.forEach( item1=>{
        return state.list.filter(item2=>{
          if( item1 == item2.price ){
            nlist.push(item2)
          }
        })
      } )
      state.list = nlist
    },
    reverse(state){
      var arr = []
      state.list.forEach(item=>{
        arr.push(item.price)
      })
      arr.sort((a,b)=>{
        return b-a
      })
      console.log(arr)
      var nlist = []
      arr.forEach( item1=>{
        return state.list.filter(item2=>{
          if( item1 == item2.price ){
            nlist.push(item2)
          }
        })
      } )
      state.list = nlist
    }
  },
  actions: {
    // async getAllList(context){
    //   const {data:res} = await axios.get('./shop.json')
    //     context.commit('getList',res)
    // }
  },
  getters:{
    getTotalPrice(state){
      var totalPrice = 0
      state.list.forEach(item=>{
        if( item.checked ){
          totalPrice += item.num * item.price
        }
      })
      return totalPrice
    }
  },
  modules: {
  }
})
